package com.smsc.headend.task.engine.service.dds.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smsc.headend.module.data.entity.MapDdsMdmWf;
import com.smsc.headend.task.engine.mapper.MapDdsMdmWfMapper;
import com.smsc.headend.task.engine.service.dds.MapDdsMdmWfService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MapDdsMdmWfServiceImpl extends ServiceImpl<MapDdsMdmWfMapper, MapDdsMdmWf> implements MapDdsMdmWfService {
    Map<Integer, Integer> mdmIdMaxSeqMap = new HashMap<>();

    @Override
    public List<MapDdsMdmWf> getMapDdsMdmWfByFileType(Integer fileType) {
        return lambdaQuery().eq(MapDdsMdmWf::getFileType, fileType).list();
    }

    @Override
    public Integer getMaxSeqSizeByCode(Integer mdmDataTypeId) {
        if (mdmIdMaxSeqMap.size() == 0) {
            mdmIdMaxSeqMap = initMdmMaxSeqMap();
        }
        return mdmIdMaxSeqMap.get(mdmDataTypeId);
    }

    private synchronized Map<Integer, Integer> initMdmMaxSeqMap() {
        if (mdmIdMaxSeqMap.size() > 0) {
            return mdmIdMaxSeqMap;
        }
        log.info("Initial mdm data id max sequence number");
        List<Map<String, Integer>> dbSeqSetting = this.getBaseMapper().listMdmIdAndMaxSeq();
        log.info("Setting: {}", JSONUtil.toJsonStr(dbSeqSetting));
        dbSeqSetting.stream().forEach(map -> {
            Integer mdmDataTypeId = Convert.toInt(map.get("mdmDataTypeId"));
            Integer maxSequence = Convert.toInt(map.get("maxSequence"));
            log.info("add -> dataTypeId:{},maxSeq:{}", mdmDataTypeId, maxSequence);
            mdmIdMaxSeqMap.put(mdmDataTypeId, maxSequence);
        });
        return this.mdmIdMaxSeqMap;
    }
}
